<?php
/**
 * Created by PhpStorm.
 * User: Mertred
 * Date: 2018/11/29
 * Time: 14:48
 */

namespace app\ai\controller;


use think\Controller;

class Common extends Controller
{

    public $suiteID;//第三方应用ID

    public $corpID;//第三方企业ID

    public $secret;//第三方应用秘钥

    public $suite_ticket;//第三方推送ticket

    public $suite_token;//授权token

    public $token;

    public $EncodingAESKey;


    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $SuiteInfo = model('SuiteAccount')->where('type',2)->find();

        $this->suiteID = $SuiteInfo['suiteID'];

        $this->corpID = $SuiteInfo['corpID'];

        $this->secret = $SuiteInfo['secret'];

        $this->suite_ticket = $SuiteInfo['suite_ticket'];

        //$this->suite_token = $this->get_suite_token($SuiteInfo);

        $this->token = $SuiteInfo['token'];     //第三方应用token

        $this->EncodingAESKey = $SuiteInfo['EncodingAESKey']; //第三方应用key


    }


    /*
     * 获取应用凭证access_token
     * */
    public function get_suite_token()
    {
        $SuiteInfo = model('SuiteAccount')->where('type',2)->find();
        if($SuiteInfo['expires_in'] >= time()){
            return $SuiteInfo['suite_token'];
        }
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token';

        $data = '{
            "suite_id":"'.$this->suiteID.'" ,
            "suite_secret": "'.$this->secret.'",
            "suite_ticket": "'.$this->suite_ticket.'",
        }';

        $ret = json_decode(https_post($url,$data));

        if(empty($ret->errcode)){
            model('SuiteAccount')->where('type',2)->update(['suite_token'=>$ret->suite_access_token,'expires_in'=>time()+$ret->expires_in]);
            return $ret->suite_access_token;
        }
        file_put_contents('../runtime/error/suite.log',date('Y-m-d H:i:s') .' token请求错误 error：'.$ret->errmsg."\r\n", FILE_APPEND );
        return 'error';
    }
}